package com.rent.writeoff.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    /**
     * 核销任务专用线程池
     */
    @Bean(name = "writeOffExecutor")
    public ThreadPoolTaskExecutor writeOffExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：CPU核心数 * 2
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        // 最大线程数：CPU核心数 * 4
        int maxPoolSize = Runtime.getRuntime().availableProcessors() * 4;

        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(10000); // 任务队列容量
        executor.setKeepAliveSeconds(60); // 空闲线程存活时间
        executor.setThreadNamePrefix("write-off-"); // 线程名前缀

        // 拒绝策略：队列满时由提交任务的线程执行，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();
        return executor;
    }
}
